package cn.com.surker.system.service.impl;

import cn.com.surker.common.Code;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.dao.SysMenuRoleDao;
import cn.com.surker.system.dao.SysOriginDao;
import cn.com.surker.system.dao.SysStationLogDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.entity.SysMenuRole;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.entity.SysStationLog;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.OriginService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年06月27 14:33
 * @desc
 */
@Service
public class OriginServiceImpl implements OriginService {

    @Resource
    private SysOriginDao originDao;

    /**
     * 部门菜单关联dao
     **/
    @Resource
    private SysMenuRoleDao menuRoleDao;

    /**数据源dao**/
    @Resource
    private DataSourceInfoDao dsDao;

    /**redis工具类**/
    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysStationLogDao stationLogDao;
//    @Autowired
//    @Qualifier("oaMysqlJdbcTemplate")
//    private JdbcTemplate oaJdbcTemplate;

    /**微信收料数据源**/
    @Autowired
    @Qualifier("sqlServerJdbcTemplate")
    private JdbcTemplate dateCenterJdbcTemplate;
    @Autowired
    HttpServletRequest request;

    /**
     * 查询用户关联的工厂
     * @return
     */
    public List<SysOrigin> queryByUidOrigin(Long uid) {
        if (StringUtils.isNull(uid))
            return null;
        List<SysOrigin> list = originDao.queryByUidOrigin(uid);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 查询已经管理数据源的公司信息
     * @return
     */
    @Cacheable(cacheNames = "queryRelationDataOrigin")
    public List<SysOrigin> queryRelationDataOrigin() {
        List<SysOrigin> list = originDao.queryRelationDataOrigin();
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 查询开通微信打卡的公司信息
     * @return
     */
    @Cacheable(cacheNames = "gpsRelationOrigin")
    public List<SysOrigin> queryGpsOrigin() {
        List<SysOrigin> list = originDao.queryGpsOrigin();
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 根据
     * @param dsId
     * @return
     */
    @Cacheable(cacheNames = "sysOriginInfo", key = "#dsId")
    public SysOrigin queryByDsId(Long dsId) {
        if (StringUtils.isNull(dsId))
            return null;

        return originDao.queryByDsId(dsId);
    }

    /**
     * 同步OA系统部门
     * @return
     */
    @CacheEvict(value = "sysOriginInfo", allEntries = true)
    public Integer synOrigin() {
//        /**同步OA系统sql**/
//        String sql = "select id,name originName,full_name fullName,parent_id pid,type_ type,org_code orgCode," +
//                "order_by sortby,wx_dept_id wxOrgId from sys_org";
//        List<Map<String, Object>> list = oaJdbcTemplate.queryForList(sql);
//        if (list == null || list.size() == 0)
//            /**未获取到部门信息**/
//            return Code.UN_ORIGIN_INFO.getCode();
//
//        for (Integer i = 0; i < list.size(); i++) {
//            SysOrigin origin = new SysOrigin();
//            Map<String, Object> map = list.get(i);
//            origin.setCreateTime(new Date());
//            if (!StringUtils.isNull(map.get("id")))
//                origin.setId(StringUtils.convertLong(map.get("id")));
//            /**部门名称**/
//            if (!StringUtils.isNull(map.get("originName")))
//                origin.setOriginName(StringUtils.convertString(map.get("originName")));
//            /**部门全称**/
//            if (!StringUtils.isNull(map.get("fullName")))
//                origin.setFullName(StringUtils.convertString(map.get("fullName")));
//            /**上级部门ID**/
//            if (!StringUtils.isNull(map.get("pid")))
//                origin.setPid(StringUtils.convertLong(map.get("pid")));
//            /**部门类型**/
//            if (!StringUtils.isNull(map.get("type"))) {
//                Integer type = StringUtils.convertInteger(map.get("type"));
//                if (type == 0)
//                    origin.setType(1);
//                else if (type == 2)
//                    origin.setType(0);
//                else if (type == 1)
//                    origin.setType(2);
//            }
//
//            if (!StringUtils.isNull(origin.getType()) && origin.getType() == 2)
//                origin.setStatus(StateEnum.ENABLED.getCode());
//            else
//                origin.setStatus(StateEnum.DISABLED.getCode());
//
//            /**部门code**/
//            if (!StringUtils.isNull(map.get("orgCode")))
//                origin.setOrgCode(StringUtils.convertString(map.get("orgCode")));
//            /**部门排序号**/
//            if (!StringUtils.isNull(map.get("sortby")))
//                origin.setSortby(StringUtils.convertInteger(map.get("sortby")));
//            /**微信部门ID**/
//            if (!StringUtils.isNull(map.get("wxOrgId")))
//                origin.setWxOrgId(StringUtils.convertLong(map.get("wxOrgId")));
//
//            Integer code = originDao.updateById(origin);
//            if (code <= 0)
//                originDao.saveOrigin(origin);
//        }
        return 0;
    }

    /**
     * 站点选择
     *
     * @param originId
     * @return
     */
    public CacheUser choseStation(String token, Long originId, Long uid, Integer type, String ip) {
        DataSourceInfo ds = dsDao.queryDSByOriginId(originId);


        SysOrigin tarOrigin = originDao.queryByOriginId(originId, uid);
        if (tarOrigin == null)
        /***您未关联部门或该站点未关联数据源,请联系管理人员**/
            return null;

        CacheUser cacheUser = (CacheUser) redisUtils.get(token);
        String name = cacheUser.getName();

        cacheUser.setOriginId(originId);
        cacheUser.setOriginName(tarOrigin.getOriginName());
        cacheUser.setOriginFullName(tarOrigin.getFullName());
        cacheUser.setDataSourceInfo(ds);
        cacheUser.setCreator(name);

        /**保存选择站点日志**/
        SysStationLog sysStationLog = new SysStationLog();
        sysStationLog.setUid(cacheUser.getId());
        sysStationLog.setStatus(StateEnum.ENABLED.getCode());
        sysStationLog.setCreateTime(new Date());
        sysStationLog.setOrgId(originId);
        sysStationLog.setFullName(tarOrigin.getFullName());
        sysStationLog.setLoginIp(ip);
        sysStationLog.setName(cacheUser.getName());
        sysStationLog.setOrgName(tarOrigin.getOriginName());
        sysStationLog.setPhone(cacheUser.getPhone());
        sysStationLog.setUsername(cacheUser.getUsername());
        if (ds != null)
            sysStationLog.setDsId(ds.getId());
        stationLogDao.insert(sysStationLog);
//        if (type == StationEnum.MIXING.getCode()) {
//            /**获取数据库联系信息**/
//            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
//            StringBuffer sql = new StringBuffer();
//            sql.append("select * from Sys_User_T where IsValid = 1 and status = 2 and username = ? order by id desc");
//            Object[] obj = {name};
//
//            List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql.toString(), obj);
//            if (listMap != null && listMap.size() > 0)
//                cacheUser.setCreatorId(StringUtils.convertInteger(listMap.get(0).get("ID")));
//            else
//                cacheUser.setCreatorId(StringUtils.convertInteger(cacheUser.getId()));
//
//            /**加入收料信息站点ID**/
//            sql = new StringBuffer("select * from Sys_Station_T where IsValid = 1 and DBName = ? ");
//
//            obj = new Object[]{ds.getCode()};
//
//            listMap = dateCenterJdbcTemplate.queryForList(sql.toString(), obj);
//            if (listMap != null && listMap.size() > 0)
//                cacheUser.setMaterialStationId(StringUtils.convertInteger(listMap.get(0).get("ID")));
//        } else if (type == StationEnum.MINE.getCode()) {
//            /**获取数据库联系信息**/
//            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
//            StringBuffer sql = new StringBuffer();
////        sql.append("select * from Sys_User_T where IsValid = 1 and status = 2 and username = ? order by id desc");
////        Object[] obj = {name};
////
////        List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql.toString(), obj);
////        if (listMap != null && listMap.size() > 0)
////            cacheUser.setCreatorId(StringUtils.convertInteger(listMap.get(0).get("ID")));
////        else
////            cacheUser.setCreatorId(StringUtils.convertInteger(cacheUser.getId()));
//
//            /**加入收料信息站点ID**/
//            sql = new StringBuffer("select * from Sys_Station_T where IsValid = 1 and u_code = ? ");
//
//            Object[] obj = new Object[]{ds.getCode()};
//
//            List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql.toString(), obj);
//            if (listMap != null && listMap.size() > 0)
//                cacheUser.setTableName(StringUtils.convertString(listMap.get(0).get("TableName")));
//
//        }

        /**加密令牌**/
        redisUtils.set(token, cacheUser, 14400L);

        return cacheUser;
    }

    /**
     * 删除关联
     *
     * @param orgId 部门ID
     * @param mid   菜单ID
     * @return
     */
    @CacheEvict(value = "sysOriginInfo", allEntries = true)
    public Integer deleteRelationOrigin(Long orgId, Long mid) {
        if (StringUtils.isNull(orgId))
            /**请选择部门**/
            return Code.CHOOSE_ORIGIN_INFO.getCode();

        if (StringUtils.isNull(orgId))
            return Code.CHOOSE_MENU_INFO.getCode();

        /**查询是否关联过**/
        QueryWrapper<SysMenuRole> query = new QueryWrapper();
        SysMenuRole role = new SysMenuRole();
        role.setOrgId(orgId);
        role.setMenuId(mid);
        query.setEntity(role);
        List<SysMenuRole> list = menuRoleDao.selectList(query);

        if (list != null && list.size() > 0) {
            /**修改已有数据**/
            Integer code = menuRoleDao.deleteById(list.get(0).getId());
            if (code > 0)
                return 0;
            else
                return -1;
        }

        return -1;
    }

    /**
     * 禁用部门
     * @param id     部门ID
     * @param status 状态
     * @return
     */
    @CacheEvict(value = "sysOriginInfo", allEntries = true)
    public Integer updateStatus(Long id, Integer status) {
        if (StringUtils.isNull(id))
            return Code.CHOOSE_ORIGIN_INFO.getCode();

        if (StringUtils.isNull(status))
            return Code.STATUS_ERROR.getCode();

        SysOrigin sysOrigin = originDao.selectById(id);
        sysOrigin.setStatus(StateEnum.DISABLED.getCode());
        sysOrigin.setStatus(status);

        Integer code = originDao.updateById(sysOrigin);

        if (code > 0)
            return 0;
        else
            return -1;
    }

    /**
     * 添加关联
     * @param orgId 部门ID
     * @param mid   菜单ID
     * @return
     */
    @CacheEvict(value = "sysOriginInfo", allEntries = true)
    public Integer saveRelationOrigin(Long orgId, Long mid) {
        if (StringUtils.isNull(orgId))
            return Code.CHOOSE_ORIGIN_INFO.getCode();

        if (StringUtils.isNull(orgId))
            return Code.CHOOSE_MENU_INFO.getCode();

        /**查询是否关联过**/
        QueryWrapper<SysMenuRole> query = new QueryWrapper();
        SysMenuRole role = new SysMenuRole();
        role.setOrgId(orgId);
        role.setMenuId(mid);
        role.setStatus(StateEnum.ENABLED.getCode());
        query.setEntity(role);
        Integer count = menuRoleDao.selectCount(query);

        if (count > 0)
            return Code.NO_REPEAT_RELATION_ORIGIN.getCode();

        role.setCreateTime(LocalDateTime.now());
        /**添加数据**/
        Integer code = menuRoleDao.insert(role);
        if (code > 0)
            return 0;
        else
            return -1;
    }

    /**
     * 根据条件查询所有的数据
     * @param dto
     * @return
     */
    public List<SysOrigin> findAll(SysOrigin dto) {
        QueryWrapper<SysOrigin> query = new QueryWrapper();
        if (!StringUtils.isNull(dto.getType()))
            query.eq("type", dto.getType());
        if(dto.getId() != null){
        	query.eq("id",dto.getId());
		}

        List<SysOrigin> list = originDao.selectList(query);

        return list;
    }

    /**
     * 查询关联菜单
     *
     * @param orgId 部门ID
     * @return
     */
    public List<Map<String, Object>> queryMenu(Long orgId) {
        if (StringUtils.isNull(orgId))
            return null;

        return originDao.queryMenu(orgId);
    }

    /**
     * 查询用户所属站点
     * @return
     */
    public List<Map<String, Object>> findUserOrigin(Integer type, Integer status, Long uid) {
        List<Map<String, Object>> list = originDao.queryUserOriginById(type, status, uid);
        if (list == null || list.size() == 0)
            list = originDao.queryUserOrigin(type, status);
        return list;
    }

    /**
     * 分页查询数据
     * @param originName page
     * @return
     */
    public IPage findByPage(String originName, Integer type, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<SysOrigin> query = new QueryWrapper();
        if (!StringUtils.isNull(originName))
            query.like("origin_name", originName);

        if (!StringUtils.isNull(type))
            query.eq("type", type);

        IPage<SysOrigin> iPage = originDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 新增数据
     * @param dto page
     * @return
     */
    public Integer saveInit(SysOrigin dto) {
        if (dto != null)
            dto.setCreateTime(new Date());

        int saveStatus = originDao.insert(dto);
        if (saveStatus > 0) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public Integer update(SysOrigin dto) {
        return null;
    }

    @Override
    public Integer delete(Long id) {
        return null;
    }

	@Override
	public SysOrigin queryByOrgId(Long orgId) {
		if (orgId == null) {
			return null;
		}
		SysOrigin origin = originDao.selectById(orgId);
		return origin;
	}
}
